import { AxiosResponse, InternalAxiosRequestConfig } from './types'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { SUCCESS_CODE, TRANSFORM_REQUEST_DATA, LOSS_REFRESH_TOKEN_CODE, LOSS_TOKEN_LOGIN_CODE } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { objToFormData } from '@/utils'
import { refreshTokenApi } from '@/api/login'
import { RefreshTokenParamsType } from '@/api/login/types'
import request from '@/axios'

const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  // if (userStore.getToken) {
  //   config.headers['Authorization'] = 'Bearer ' + userStore.getToken
  // }
  const userStore = useUserStoreWithOut()

  if (config.method === 'post' && config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
    config.data = qs.stringify(config.data)
  } else if (TRANSFORM_REQUEST_DATA && config.method === 'post' && config.headers['Content-Type'] === 'multipart/form-data') {
    config.data = objToFormData(config.data)
  }
  if ((config.method === 'get' || config.method === 'delete') && config.params) {
    let url = config.url as string
    url += '?'
    const keys = Object.keys(config.params)
    for (const key of keys) {
      if (config.params[key] !== void 0 && config.params[key] !== null) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
    }
    url = url.substring(0, url.length - 1)
    config.params = {}
    config.url = url
  }
  return config
}

const defaultResponseInterceptors = async (response: AxiosResponse) => {
  const userStore = useUserStoreWithOut()

  // if (response?.config?.responseType === 'blob') {
  //   // 如果是文件流，直接过
  //   return response
  // } else
  if (response.data.code === SUCCESS_CODE) {
    return response.data
  } else if (response.data.code === LOSS_REFRESH_TOKEN_CODE) {
    try {
      const params: RefreshTokenParamsType = {
        loseToken: userStore.getToken
      }
      const tokenResponse = await refreshTokenApi(params)
      if (tokenResponse.code === SUCCESS_CODE) {
        if (tokenResponse.data.token) {
          userStore.setToken(tokenResponse.data.token)
          const retryResponse = await request.retryRequest(response)
          return retryResponse.data
        } else {
          userStore.logout()
        }
      } else {
        userStore.logout()
      }
    } catch (e) {
      userStore.logout()
    }
  } else if (response.data.code === LOSS_TOKEN_LOGIN_CODE) {
    userStore.logout()
  } else {
    ElMessage.error(response?.data?.message)
  }
}

export { defaultResponseInterceptors, defaultRequestInterceptors }
